from fastapi import APIRouter, Request
from pyJianYingDraft import CapCut_Text_intro, Text_intro, CapCut_Text_outro, Text_outro, CapCut_Text_loop_anim, \
    Text_loop_anim, Font_type, Text_style, Text_border
from pyJianYingDraft.text_segment import TextStyleRange
from src.constants.resultcode import ResultCode
from .base import RouterMeta
import config
from src.utils.response import ApiResponse
from src.schemas.text import DraftAddTextRequest, DraftAddSubtitleRequest
from src.service.add_text import add_text_impl
from src.schemas.draft import DraftDataResponse
from src.utils.util import hex_to_rgb
from src.utils.logger import get_logger
from src.service.add_subtitle import add_subtitle_impl

logger = get_logger("capcut")

router = APIRouter()

@router.get("/intro_types",name="获取文本入场动画")
def get_text_intro_types(request: Request):
    """
    获取文本入场动画
    """
    try:
        text_intro_types = []
        if config.IS_CAPCUT_ENV:
            for name, member in CapCut_Text_intro.__members__.items():
                text_intro_types.append({
                    "intro_name": name
                })
        else:
            for name, member in Text_intro.__members__.items():
                text_intro_types.append({
                    "intro_name": name
                })
        return ApiResponse.success(
            data=text_intro_types
        )
    except Exception as e:
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取文本入场动画失败: {str(e)}",
        )

@router.get("/outro_types",name="获取文本出场动画")
def get_text_outro_types(request: Request):
    """
    获取文本出场动画
    """
    try:
        text_outro_types = []
        if config.IS_CAPCUT_ENV:
            for name, member in CapCut_Text_outro.__members__.items():
                text_outro_types.append({
                    "outro_name": name
                })
        else:
            for name, member in Text_outro.__members__.items():
                text_outro_types.append({
                    "outro_name": name
                })
        return ApiResponse.success(
            data=text_outro_types
        )
    except Exception as e:
        logger.error(f"获取文本出场动画失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取文本出场动画失败: {str(e)}",
        )


@router.get("/loop_anim_types",name="获取文本循环动画")
def get_text_loop_anim_types(request: Request):
    """
    获取文本循环动画效果
    """
    try:
        text_loop_anim_types = []
        if config.IS_CAPCUT_ENV:
            # Return text loop animation types in CapCut environment
            for name, member in CapCut_Text_loop_anim.__members__.items():
                text_loop_anim_types.append({
                    "loop_anim_name": name
                })
        else:
            # Return text loop animation types in JianYing environment
            for name, member in Text_loop_anim.__members__.items():
                text_loop_anim_types.append({
                    "loop_anim_name": name
                })

        return ApiResponse.success(
            data=text_loop_anim_types
        )
    except Exception as e:
        logger.error(f"获取文本循环动画效果失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取文本循环动画效果失败: {str(e)}",
        )


@router.get("/font_types",name="获取可用字体")
def get_font_types(request: Request):
    """
    获取可用字体
    """
    try:
        font_types = []

        # Return font types in JianYing environment
        for name, member in Font_type.__members__.items():
            font_types.append({
                "font_name": name
            })
        return ApiResponse.success(
            data=font_types
        )
    except Exception as e:
        logger.error(f"获取可用字体失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取可用字体失败: {str(e)}",
        )

@router.get("/artist_types",name="获取可用花字")
def get_font_types(request: Request):
    """
    获取可用花字
    """
    try:
        artist_types_list = []

        return ApiResponse.success(
            data=artist_types_list
        )
    except Exception as e:
        logger.error(f"获取可用花字失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"获取可用花字失败: {str(e)}",
        )


@router.post("/add_text", name="添加文本", response_model=DraftDataResponse)
async def add_text_api(request: Request, text_request: DraftAddTextRequest):
    """
    向草稿添加文本元素
    支持多种文本样式、边框、背景和阴影效果，可通过text_styles参数设置文本不同部分的样式。
    """
    try:
        # 处理文本样式范围（改写重点）
        text_styles =[]
        if text_request.text_styles:
            text_styles = []
            for style_range in text_request.text_styles:
                # 获取样式数据（如果存在）
                start_pos = style_range.get('start', 0)
                end_pos = style_range.get('end', 0)
                # 3. 获取样式数据（直接使用字典，无需调用.dict()）
                style_data = style_range.get('style', {})
                # 4. 获取边框数据（同样使用字典访问）
                border_data = style_range.get('border', {})
                # 创建文本样式对象（匹配原代码逻辑）
                style = Text_style(
                    size=style_data.get('size', int(text_request.font_size)),
                    bold=style_data.get('bold', False),
                    italic=style_data.get('italic', False),
                    underline=style_data.get('underline', False),
                    color=hex_to_rgb(style_data.get('color', text_request.font_color)),
                    alpha=style_data.get('alpha', text_request.font_alpha),
                    align=style_data.get('align', 1),
                    vertical=style_data.get('vertical', text_request.vertical),
                    letter_spacing=style_data.get('letter_spacing', 0),
                    line_spacing=style_data.get('line_spacing', 0)
                )
                # 创建边框对象（如果宽度大于0）
                border = None
                border_width = border_data.get('width', text_request.border_width)
                if border_width > 0:
                    border = Text_border(
                        alpha=border_data.get('alpha', text_request.border_alpha),
                        color=hex_to_rgb(border_data.get('color', text_request.border_color)),
                        width=int(border_width)
                    )
                # 创建文本样式范围对象
                text_style = TextStyleRange(
                    start=start_pos,
                    end=end_pos,
                    style=style,
                    border=border,
                    font_str=style_range.get('font', text_request.font)  # 字典访问
                )
                text_styles.append(text_style)
        draft_result = add_text_impl(text=text_request.text,
            start=text_request.start,
            end=text_request.end,
            draft_id=text_request.draft_id,
            transform_x=text_request.transform_x,
            transform_y=text_request.transform_y,
            font=text_request.font,
            font_color=text_request.font_color,
            font_size=int(text_request.font_size),
            font_alpha=text_request.font_alpha,
            track_name=text_request.track_name,
            vertical=text_request.vertical,
            outro_animation=text_request.outro_animation,
            outro_duration=text_request.outro_duration,
            intro_animation=text_request.intro_animation,
            intro_duration=text_request.intro_duration,
            width=text_request.width,
            height=text_request.height,
            fixed_width=text_request.fixed_width,
            fixed_height=text_request.fixed_height,
            border_alpha=text_request.border_alpha,
            border_color=text_request.border_color,
            border_width=int(text_request.border_width),
            background_color=text_request.background_color,
            background_style=text_request.background_style,
            background_alpha=text_request.background_alpha,
            background_round_radius=text_request.background_round_radius,
            background_height=text_request.background_height,
            background_width=text_request.background_width,
            background_horizontal_offset=text_request.background_horizontal_offset,
            background_vertical_offset=text_request.background_vertical_offset,
            shadow_enabled=text_request.shadow_enabled,
            shadow_alpha=text_request.shadow_alpha,
            shadow_angle=text_request.shadow_angle,
            shadow_color=text_request.shadow_color,
            shadow_distance=text_request.shadow_distance,
            shadow_smoothing=text_request.shadow_smoothing,
            bubble_effect_id=text_request.bubble_effect_id,
            bubble_resource_id=text_request.bubble_resource_id,
            effect_effect_id=text_request.effect_effect_id,
            text_styles=text_styles,
            letter_spacing=text_request.letter_spacing,
            line_spacing=text_request.line_spacing)
        return ApiResponse.success(data=draft_result)
    except Exception as e:
        logger.error(f"添加文本异常: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"添加文本失败: {str(e)}"
        )

@router.post("/add_subtitle", name="添加字幕", response_model=DraftDataResponse)
async def add_subtitle_api(request: Request, subtitle_request: DraftAddSubtitleRequest):
    """
    向草稿添加字幕元素
    """
    try:
        draft_result = add_subtitle_impl(srt_path=subtitle_request.srt,
                draft_id=subtitle_request.draft_id,
                track_name=subtitle_request.track_name,
                time_offset=subtitle_request.time_offset,
                # Font style parameters
                font=subtitle_request.font,
                font_size=subtitle_request.font_size,
                bold=subtitle_request.bold,
                italic=subtitle_request.italic,
                underline=subtitle_request.underline,
                font_color=subtitle_request.font_color,
                vertical=subtitle_request.vertical,  # New: pass vertical parameter
                alpha=subtitle_request.alpha,  # New: pass alpha parameter
                border_alpha=subtitle_request.border_alpha,
                border_color=subtitle_request.border_color,
                border_width=subtitle_request.border_width,
                background_color=subtitle_request.background_color,
                background_style=subtitle_request.background_style,
                background_alpha=subtitle_request.background_alpha,
                # Image adjustment parameters
                transform_x=subtitle_request.transform_x,
                transform_y=subtitle_request.transform_y,
                scale_x=subtitle_request.scale_x,
                scale_y=subtitle_request.scale_y,
                rotation=subtitle_request.rotation,
                width=subtitle_request.width,
                height=subtitle_request.height)
        return ApiResponse.success(data=draft_result)
    except Exception as e:
        logger.error(f"添加字幕异常: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"添加字幕失败: {str(e)}"
        )

# 路由元数据配置
meta = RouterMeta(
    router=router,
    prefix="/text",
    tags=["文本"]
)